package com.googlecode.connectlet.machine.provider.param;

import java.security.AlgorithmParameterGeneratorSpi;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import com.googlecode.connectlet.machine.provider.MachineConnection;
import com.googlecode.connectlet.machine.provider.MachineProvider;

public final class MachineParameterGenerator extends AlgorithmParameterGeneratorSpi {
	private MachineConnection conn;
	private byte[] key;

	@Override
	protected AlgorithmParameters engineGenerateParameters() {
		try {
			AlgorithmParameters params = AlgorithmParameters.
					getInstance("Machine", MachineProvider.getInstance());
			params.init(conn.generateMachineKey(key));
			return params;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Deprecated
	@Override
	protected void engineInit(int size, SecureRandom random) {
		throw new UnsupportedOperationException();
	}

	@Override
	protected void engineInit(AlgorithmParameterSpec genParamSpec,
			SecureRandom random) throws InvalidAlgorithmParameterException {
		if (genParamSpec instanceof MachineConnection) {
			conn = (MachineConnection) genParamSpec;
			key = (conn instanceof MachineConnectionWithKey) ?
					((MachineConnectionWithKey) conn).getKey() : null;
		} else {
			throw new InvalidAlgorithmParameterException("MachineConnection required");
		}
	}
}